package a06_栈与队列;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * <p>
 * a08_前K个高频元素复习4
 * </p>
 *
 * @author flyduck
 * @since 2025/5/19
 */
public class a08_前K个高频元素复习4 {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2)));
    }
    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int num : nums) {
            if (!map.containsKey(num)) {
                map.put(num, 1);
            }else {
                map.put(num, map.get(num) + 1);
            }
        }

        PriorityQueue<int[]> priorityQueue = new PriorityQueue<int[]>((item1,item2) -> {
            return item2[1] - item1[1];
        });
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            priorityQueue.add(new int[]{entry.getKey(),entry.getValue()});
        }

        int[] result = new int[k];
        for (int i = 0; i < result.length; i++) {
            result[i] = priorityQueue.poll()[0];
        }
        return result;
    }
}
